﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using CCWin;

namespace SvipQuery
{
    public partial class FrmLogin : Skin_Mac
    {
        private string gtk32 = string.Empty;
        private string gtk = string.Empty;
        private string uin = string.Empty;
        private string cookies = string.Empty;
        public LoginUser loginUser;

        public FrmLogin()
        {
            InitializeComponent();
        }

        private void Browser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if (!e.Url.AbsoluteUri.StartsWith("http://id.qq.com/index.html")) return;
            if (!CheckLogin(Browser.Document.Cookie)) return;
            Invoke(new MethodInvoker(delegate
            {
                loginUser = new LoginUser
                {
                    Qq = uin,
                    Cookies = cookies,
                    Gtk = gtk,
                    Gtk32 = gtk32
                };
                Browser.Stop();
                DialogResult = DialogResult.OK;
            }));
        }

        private bool CheckLogin(string c)
        {
            var xjHttp = new XJHTTP();
            var cookieList = xjHttp.GetAllCookie(xjHttp.StringToCookie("id.qq.com", c));
            var skey = cookieList.FirstOrDefault(cookie => cookie.Name == "skey")?.Value;
            if (skey == "")
                return false;
            gtk = Helpers.GetGtk(skey);
            gtk32 = Helpers.Get32Gtk(skey);
            uin = cookieList.FirstOrDefault(cookie => cookie.Name == "p_uin")?.Value.Replace("o", "").TrimStart('0');
            cookieList.ForEach(cl => cookies += (cl.Name + "=" + cl.Value + ";"));
            return gtk != "" && uin != "";
        }
    }
}
